<template>
  <div class="ebook-reader">
    <div id="read"></div>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex';
  import Epub from 'epubjs';
  global.ePub = Epub;
  export default {
    name: 'EbookReader',
    mounted(){
      //解析字符串获得部分路径,放到全局状态管理
      const path = this.$route.params.fileName.split('|').join('/');
      this.$store.dispatch("setFileName",path).then(()=>{
          this.initEpub();
      });
    },
    methods:{
      initEpub(){
        //拼接得到完整路径
        const baseUrl = 'http://47.95.243.232:9000/epub/';
        const fullUrl = `${baseUrl}${this.fileName}.epub`;
        //使用epub实例化电子书
        this.book = new Epub(fullUrl);
        this.rendition = this.book.renderTo('read',{
          width: innerWidth,
          height: innerHeight,
          method: 'default'
        });
        //显示电子书
        this.rendition.display();
        //绑定事件到iframe
        this.rendition.on('touchstart',event =>{
            //滑动开始的位置
            this.touchStartX = event.changedTouches[0].clientX;
            //开始时间
            this.startTime = event.timeStamp;
        });
        this.rendition.on('touchend',event =>{
            //获取 滑动从开始到结束后的偏移大小
            const offsetX = event.changedTouches[0].clientX - this.touchStartX;
            //获取 执行完毕时间
            const time = event.timeStamp - this.startTime;
            console.log(`偏移大小：${offsetX}　总用时：${time}毫秒`);
            if(time < 500 && offsetX > 40){
                //上一页
                this.prevPage();
            }else if(time < 500 && offsetX < -40){
                //下一页
                this.nextPage();
            }else{
                this.showTitleAndMenu();
            }
            event.preventDefault();
            event.stopPropagation();
        });
      },
      prevPage(){
        if(this.rendition){
          this.rendition.prev();
        }
      },
      nextPage(){
        if(this.rendition){
          this.rendition.next();
        }
      },
      showTitleAndMenu(){
        this.$store.dispatch("setOperationToggle", !this.operationToggle);
      }
    },computed:{
        ...mapGetters(['fileName','operationToggle'])
    }
  };
</script>

<style scoped lang="stylus">

</style>
